package cn.gailvlun.gll.chatkit.dialog

import android.graphics.drawable.Drawable
import cn.gailvlun.gll.chatkit.R
import cn.gailvlun.gll.chatlib.NotificationType
import cn.gailvlun.gll.chatlib.bean.SystemNotification
import cn.gailvlun.gll.chatlib.db.ChatDB2
import cn.gailvlun.gll.net.base.friend.FriendNotification
import com.blankj.utilcode.util.Utils
import io.realm.Realm
import java.util.*


class NotificationViewModel {
    var header: Drawable? = null
    var title: String? = null
    var content: String? = null
    var created: Date? = null
    var unreadCount: Long? = null

    companion object {
        fun transform(systemNotification: SystemNotification?): NotificationViewModel {
            val viewModel = NotificationViewModel()
            viewModel.header = Utils.getApp().resources.getDrawable(R.drawable.ic_system_noti)
            viewModel.title = "小概君"

            if (systemNotification != null) {
                viewModel.content = "你有一条来自${getContent(systemNotification)}的消息"
                viewModel.created = systemNotification.created

                val realm = Realm.getInstance(ChatDB2.getConfiguration())
                val unreadCount = realm.where(SystemNotification::class.java)


                        .equalTo("unread", true)
                        .count()

                viewModel.unreadCount = unreadCount

                realm.close()
            }

            return viewModel
        }

        private fun getContent(systemNotification: SystemNotification): String {
            return when (systemNotification.type) {
                NotificationType.emotionComment,
                NotificationType.emotionHeart -> "情绪博物馆"
                NotificationType.hotelHeart,
                NotificationType.hotelComment -> "失眠旅馆"
                NotificationType.roomOpen,
                NotificationType.roomWillBeClosed,
                NotificationType.roomReviewed,
                NotificationType.roomAbortion,
                NotificationType.roomClosed -> "52Hz公寓"
                else -> "未知"
            }
        }

        fun transform(friendNotification: FriendNotification): NotificationViewModel {
            val viewModel = NotificationViewModel()
            viewModel.header = Utils.getApp().resources.getDrawable(R.drawable.icon_msg_default)
            viewModel.title = "好友通知"
            viewModel.created = friendNotification.created

            val realm = Realm.getInstance(ChatDB2.getConfiguration())
            val unreadResults = realm.where(FriendNotification::class.java)
                    .equalTo("status", 0 as Int)
                    .findAll()

            viewModel.unreadCount = unreadResults.size.toLong()
            if (viewModel.unreadCount != 0L) {
                viewModel.content = "${unreadResults[0]?.owner?.name}等${viewModel.unreadCount}人申请加你为好友"
            }

            realm.close()
            return viewModel
        }
    }
}